<?php

namespace app\admin\controller\yuncunchu;

use app\common\controller\Backend;
use app\common\service\YuncunchuService;

/**
 * 云存储使用示例
 */
class Example extends Backend
{
    /**
     * 示例页面
     */
    public function index()
    {
        return $this->view->fetch();
    }

    /**
     * 上传示例
     */
    public function upload()
    {
        $file = $this->request->file('file');
        
        if (!$file) {
            $this->error('请选择文件');
        }
        
        try {
            // 使用默认配置上传
            $service = new YuncunchuService();
            $result = $service->upload($file, 'example', 'upload');
            
            if ($result['success']) {
                $this->success('上传成功', null, [
                    'file_id' => $result['file_id'],
                    'file_url' => $result['file_url'],
                    'file_name' => $result['file_name']
                ]);
            } else {
                $this->error($result['message']);
            }
        } catch (\Exception $e) {
            $this->error('上传失败：' . $e->getMessage());
        }
    }

    /**
     * 获取文件列表
     */
    public function files()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        
        $files = \app\admin\model\yuncunchu\File::with(['config'])
            ->where('upload_module', 'example')
            ->order('id', 'desc')
            ->paginate($limit, false, ['page' => $page]);
        
        $this->success('获取成功', null, [
            'total' => $files->total(),
            'rows' => $files->items()
        ]);
    }

    /**
     * 删除文件示例
     */
    public function delete()
    {
        $fileId = $this->request->post('file_id');
        
        if (!$fileId) {
            $this->error('请指定文件ID');
        }
        
        try {
            $service = new YuncunchuService();
            $service->delete($fileId);
            $this->success('删除成功');
        } catch (\Exception $e) {
            $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取统计信息
     */
    public function statistics()
    {
        try {
            $service = new YuncunchuService();
            $stats = $service->getStatistics();
            
            $this->success('获取成功', null, $stats);
        } catch (\Exception $e) {
            $this->error('获取统计信息失败：' . $e->getMessage());
        }
    }
}
